<?php

session_start();

define('ROOT', dirname(__FILE__));
require(ROOT . '/config/constant.php');
require(ROOT . '/lib/function.php');
require(ROOT . '/lib/Controller.php');
require(ROOT . '/lib/DB.php');
require(ROOT . '/lib/Model.php');

$global = require(ROOT . '/config/global.php');

$requestSegments = array();

if (strpos($_SERVER['REQUEST_URI'], '?') === false) {
	$controller = $global['defaultController'];
	$action = $global['defaultAction'];
} else {
	$uriSegments = explode('?', $_SERVER['REQUEST_URI']);
	if (strpos($uriSegments[1], '&') !== false) {
		$segments = explode('&', $uriSegments[1]);
		$pathinfo = $segments[0];
	} else {
		$pathinfo = $uriSegments[1];
	}

	if (strpos($pathinfo, '/') === false) {
		$controller = str_replace(array('\\', '/', '.'), '', $pathinfo);
		$action = $global['defaultAction'];
	} else {
		$parameterSegments = explode('/', $pathinfo);
		$controller = str_replace(array('\\', '.'), '', array_shift($parameterSegments));
		$action = array_shift($parameterSegments);
		if (empty($action)) {
			$action = $global['defaultAction'];
		}

		if (isset($parameterSegments[0])) {
			$requestSegments = $parameterSegments;
		}
	}
}

$controllerClass = (strpos($controller, '_') === false ? ucfirst($controller) : _2uc($controller)) . 'Controller';

$actionName = lcfirst((strpos($action, '_') === false ? $action : _2uc($controller))) . 'Action';

$controllerPath = ROOT . '/controllers/' . $controllerClass . '.class.php';

if (!file_exists($controllerPath)) {
	echo 'The page is not found! 404! error 0001';
	exit();
}

require($controllerPath);

if (!class_exists($controllerClass)) {
	echo 'The page is not found! 404! error 0002';
	exit();
}

$controllerHandle = new $controllerClass();

if (!method_exists($controllerHandle, $actionName)) {
	echo 'The page is not found! 404! error 0003';
	exit();
}

call_user_func_array(array($controllerHandle, $actionName), array($requestSegments));
?>